package com.hzp.net.netty.client;

import com.hzp.net.netty.client.handler.NettyClientInHandlerFilter;
import com.hzp.net.netty.client.handler.NettyClientOutHandlerFilter;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NioNettyClient {

    public NioNettyClient(String host,Integer port){
        // 首先，netty通过ServerBootstrap启动服务端
        Bootstrap client = new Bootstrap();

        //第1步 定义线程组，处理读写和链接事件，没有了accept事件
        EventLoopGroup group = new NioEventLoopGroup();
        client.group(group );

        //第2步 绑定客户端通道
        client.channel(NioSocketChannel.class);

        //第3步 给NIoSocketChannel初始化handler， 处理读写事件
        client.handler(new ChannelInitializer<NioSocketChannel>() {  //通道是NioSocketChannel
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
                //字符串编码器，一定要加在SimpleClientHandler 的上面
                ch.pipeline().addLast(new NettyClientInHandlerFilter())
                        .addLast(new NettyClientOutHandlerFilter());
            }
        });

        //连接服务器
        try {
            ChannelFuture future = client.connect(host, port).sync();
            //当通道关闭了，就继续往下走
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                group.shutdownGracefully().sync();
            } catch (InterruptedException e) {
            }
        }
    }

    public static void main(String[] args) {
        new NioNettyClient("localhost",888);
    }
}
